package com.hopool.shop.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class BaseDao {
	protected SessionFactory sessionFactory;
	protected HibernateTemplate hibernateTemplate;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	public Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	
	public List page(Object exampleobj,Integer firstResult,
			Integer maxResults,String orderType,String... customProperties){
		Example example = 
			Example.create(exampleobj)
				   .excludeZeroes()
				   .ignoreCase()
				   .enableLike();
		Criteria crt = getSession().createCriteria(exampleobj.getClass());
		crt.add(example);
		if(orderType!=null&&PageUtil.isExistCreateTimeProp(exampleobj)){
			if(orderType.equals(PageUtil.ORDER_ASC)){
				crt.addOrder(Order.asc(PageUtil.DEFAULT_ORDER_PROPERTY));
			}else{
				crt.addOrder(Order.desc(PageUtil.DEFAULT_ORDER_PROPERTY));
			}
		}
		this.addCustomProperties(exampleobj, crt, customProperties);
		crt.setFirstResult(firstResult);
		crt.setMaxResults(maxResults);
		List list = crt.list();
		return list;
	}
	public Integer count(Object exampleobj,String... customProperties){
		Example example = 
			Example.create(exampleobj)
				   .excludeZeroes()
				   .ignoreCase()
				   .enableLike();
		Criteria crt = getSession().createCriteria(exampleobj.getClass());
		this.addCustomProperties(exampleobj, crt, customProperties);
		crt.setProjection(Projections.rowCount());
		crt.add(example);
		return (Integer) crt.uniqueResult();
	}
	private void addCustomProperties(Object exampleobj,Criteria crt,String... customProperties){
		for(String customProperty:customProperties){
			Object obj = PageUtil.getCustomProperty(exampleobj, customProperty);
			if(obj!=null){
				crt.createCriteria(customProperty).add(Example.create(obj));
			}
		}
	}
	
}
